<template>
  <div>
    <div class="box">
      <el-row>
        <el-col :span="12">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            :rules="rules"
            label-width="180px"
            class="demo-ruleForm"
          >
            <el-form-item label="上级类别" prop="parentId">
              <el-cascader
                v-model="ruleForm.parentId"
                style="width: 100%"
                :placeholder="parentCategory ? parentCategory.name : '点击选择上级类别，否则默认一级类别'"
                size="small"
                :props="props"
              />
            </el-form-item>
            <el-form-item label="类别名称" prop="name">
              <el-input v-model="ruleForm.name" size="small" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="ruleForm.sort" size="small" />（排序值越大越靠前）
            </el-form-item>
            <el-form-item label="是否启用" prop="enable">
              <el-switch
                v-model="ruleForm.enable"
                :active-value="1"
                :inactive-value="0"
                active-color="#1aa"
                inactive-color="#aaa"
              />
            </el-form-item>
            <el-form-item label="是否在导航栏中显示" prop="isDisplay">
              <el-switch
                v-model="ruleForm.isDisplay"
                :active-value="1"
                :inactive-value="0"
                active-color="#1aa"
                inactive-color="#aaa"
              />
            </el-form-item>
            <el-form-item label="类别图标" prop="icon">
              <input v-model="ruleForm.icon" type="hidden">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                name="logo"
                :data="{ categoryNamePinyin: ruleForm.name }"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="UPLOAD_URL"
                :headers="tokenHeader"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 130px; height: auto;">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
            <el-form-item label="关键词" prop="keywords">
              <el-input v-model="ruleForm.keywords" size="small" />
            </el-form-item>
            <div class="divider" />
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >确认</el-button>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import * as api from '@/api/category'
import { getToken } from '@/utils/auth'
export default {
  data() {
    return {
      categoryId: null,
      parentCategory: null,
      // value: '',
      UPLOAD_URL: `${process.env.VUE_APP_BASE_API}upload/category-logo`,
      imageUrl: '',
      tokenHeader: { Authorization: getToken() },
      ruleForm: {
        name: '',
        parentId: [0], // 默认父类别为根类别
        keywords: '',
        sort: 0,
        icon: '',
        enable: 1,
        isDisplay: 1
      },
      rules: {
        name: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序序号', trigger: 'blur' }],
        keywords: [
          {
            required: true,
            message: '请输入关键词（多个关键词以英文逗号分隔）',
            trigger: 'blur'
          }
        ]
      },
      props: {
        lazy: true, // 懒加载
        checkStrictly: true, // 设置为true，可以选择中间类别
        lazyLoad: (node, resolve) => {
          // node 是被选定是节点，resolve是一个回调函数，用于将数据返回给组件
          /** 定义懒加载方式 */
          console.log('选择的当前节点：', node)
          let parentId = 0
          // 当时被点击的节点不是根节点时，parentId为当前节点的id
          if (!node.root) {
            parentId = node.data.value
          }
          api.queryByParentId(parentId).then((res) => {
            console.log('加载子类别：', res)
            const children = res.data
            // 整理数据结构, 返回类别数组 [{label:'类别名', value:'类别id'}...]
            const nodes = []
            children.forEach((category) => {
              nodes.push({
                label: category.name, // 类别名称
                value: category.id, // 类别id
                leaf: category.isParent !== 1 // 是否为叶子节点
              })
            })
            console.log('整理后的类别数组：', nodes)
            // 将数据返回给组件
            resolve(nodes)
          })
        }
      }
    }
  },

  /** 页面加载完毕执行 */
  mounted() {
    // 加载当前选中的类别信息， 回填数据
    this.categoryId = this.$route.params.id
    api.getCategory(this.categoryId).then((res) => {
      console.log('根据ID查询类别详情：', res)
      this.ruleForm = res.data
      const icon = res.data.icon
      if (icon.startsWith('http')) {
        this.imageUrl = icon
      } else {
        this.imageUrl = process.env.VUE_APP_BASE_API + icon.substring(1)
      }
      // 查询父类别信息，回填数据
      api.getCategory(this.ruleForm.parentId).then((res) => {
        console.log('根据ID查询类别详情：', res)
        this.parentCategory = res.data
        // this.value = this.ruleForm.parentId
      })
    })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.ruleForm.icon = res.data
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    beforeAvatarUpload(file) {
      const isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPGPNG && isLt5M
    },

    /** 提交表单 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm)
          // 由于cascader组件返回的parentId为层级数组，所以重置表单中parentId与depth字段
          const parentIds = this.ruleForm.parentId
          this.ruleForm.parentId = parentIds[parentIds.length - 1]
          this.ruleForm.depth = parentIds.length
          // 提交表单
          api.updateCategory(this.categoryId, this.ruleForm).then((res) => {
            console.log('更新类别', res)
            this.$message({
              showClose: true,
              message: '恭喜你，类别更新成功',
              type: 'success'
            })
            // 重建缓存后 回首页
            // return this.categoryApi.rebuildCache()
            // this.$route.push({ name: 'Category', params: { parentId: this.ruleForm.parentId }})
          }).then(res => {
            console.log('重建缓存：' + res)
            // this.$router.push('/home/product/category')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
